package  com.syqc.sensor.water

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.github.mikephil.charting.data.Entry
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.ListInfo
import com.syqc.entity.OilPoint
import com.syqc.net.ServiceHelper

class WaterChartVM : AutoDisposeViewModel() {
    //真实值
    private val oilV0Data = ArrayList<Entry>()

    //优化值
    private val oilVData = ArrayList<Entry>()

    //里程
    private val kmData = ArrayList<Entry>()

    //速度
    private val speedData = ArrayList<Entry>()
    val details = ArrayList<OilPoint>()
    val timeData = ArrayList<String>()
    val addDetail = ArrayList<ListInfo>()

    private val dataLive = MutableLiveData<ArrayList<ArrayList<Entry>>>()

    fun oilDetail(): LiveData<ArrayList<ArrayList<Entry>>> = dataLive
    var precision: String = "2"

    fun getDayData(carId: String, day: String, cfg: String) {
        toastLoading(true)
        ServiceHelper.getRepository()
            .getNodes(carId, day, cfg)
            .autoDispose(this)
            .subscribe({
                toastLoading(false)
                handleData(it)
            }, error)
    }


    fun handleData(data: ArrayList<OilPoint>) {
        details.clear()
        details.addAll(data)
        data.forEachIndexed { index, detail ->
            oilV0Data.add(Entry(index.toFloat(), detail.m))
            oilVData.add(Entry(index.toFloat(), detail.v))
            kmData.add(Entry(index.toFloat(), (detail.mile / 1000.00).toFloat()))
            speedData.add(Entry(index.toFloat(), detail.s.toFloat()))
            timeData.add(detail.time.substring(11))
        }
        val dataEntity = ArrayList<ArrayList<Entry>>()
        dataEntity.add(oilV0Data)
        dataEntity.add(oilVData)
        dataEntity.add(kmData)
        dataEntity.add(speedData)
        dataLive.postValue(dataEntity)
    }

    /**
     * 区分添加和漏油
     *
     */
    fun handleAddLeak(list: String?) {
        if (list.isNullOrEmpty())return
        val infos = GsonUtil.formArrayList(list, ListInfo::class.java)
        addDetail.clear()
        infos.forEach {
            when (it.t) {
                "U" -> {
                    addDetail.add(it)
                }
            }
        }
    }

}